﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using TwainDotNet;
using System.IO;
using TwainDotNet.WinFroms;

namespace Sbk_Manage
{
    using TwainDotNet.TwainNative;

    public partial class Frm_Scan : Form
    {
        private static AreaSettings AreaSettings = new AreaSettings(Units.Centimeters, 0.1f, 5.7f, 0.1F + 2.6f, 5.7f + 2.6f);

        Twain _twain;
        ScanSettings _settings;

        public Frm_Scan()
        {
            InitializeComponent();
            this.CenterToScreen();
            _twain = new Twain(new WinFormsWindowMessageHook(this));
            _twain.TransferImage += delegate(Object sender, TransferImageEventArgs args)
            {
                if (args.Image != null)
                {
                    pictureBox1.Image = args.Image;

                    widthLabel.Text = "宽度: " + pictureBox1.Image.Width;
                    heightLabel.Text = "高度: " + pictureBox1.Image.Height;
                }
            };
            _twain.ScanningComplete += delegate
            {
                Enabled = true;
            };
           
        }

        private void selectSource_Click(object sender, EventArgs e)
        {
            _twain.SelectSource();
        }

        private void scan_Click(object sender, EventArgs e)
        {
            Enabled = false;

            _settings = new ScanSettings();
            _settings.UseDocumentFeeder = useAdfCheckBox.Checked;
            _settings.ShowTwainUI = useUICheckBox.Checked;
            _settings.ShowProgressIndicatorUI = showProgressIndicatorUICheckBox.Checked;
            _settings.UseDuplex = useDuplexCheckBox.Checked;
            _settings.Resolution =
                blackAndWhiteCheckBox.Checked
                ? ResolutionSettings.Fax : ResolutionSettings.ColourPhotocopier;
            _settings.Area = !checkBoxArea.Checked ? null : AreaSettings;
            _settings.ShouldTransferAllPages = true;

            _settings.Rotation = new RotationSettings()
            {
                AutomaticRotate = autoRotateCheckBox.Checked,
                AutomaticBorderDetection = autoDetectBorderCheckBox.Checked
            };

            try
            {
                _twain.StartScanning(_settings);
            }
            catch (TwainException ex)
            {
                MessageBox.Show(ex.Message);
                Enabled = true;
            }
        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image != null)
            {
                string PathImg = ImgFolder + @"\" + CurHtqdrq;
                if (Directory.Exists(PathImg) == false)
                {
                    Directory.CreateDirectory(PathImg);
                }
                PathImg +=  @"\" + string.Format("{0}-{1}",CurHtbh,CurHtID);
                if (Directory.Exists(PathImg) == false)
                {
                    Directory.CreateDirectory(PathImg);
                }
                string filename = string.Format("Ht_{0}", Guid.NewGuid().ToString("N"));
                string strFileName = string.Format(@"{0}\{1}.jpg", PathImg, filename);
                pictureBox1.Image.Save(strFileName,System.Drawing.Imaging.ImageFormat.Jpeg);
                string sqlstr = "select max(timestamp) from multi_media_info where media_type=1 and study_no=" + CurHtID;
                object imgXh = Program.SqliteDB.ExecuteScalar(sqlstr);
                int imgCurXh = 0;
                if (imgXh != null && imgXh.ToString() != "")
                {
                    imgCurXh += 1;
                }
                else
                {
                    imgCurXh = 0;
                }
                //--------- 插入本地库 保存本次试验记录到数据库--------------
                List<object> lstRealDataFile = new List<object>();
                lstRealDataFile.Add(CurHtID);
                lstRealDataFile.Add("1");
                lstRealDataFile.Add(PathImg.Replace(Program.APPdirPath,""));
                lstRealDataFile.Add(filename+".jpg");
                lstRealDataFile.Add(CurHtbh);
                lstRealDataFile.Add(CurHtmc);
                //用data_time.ToString("s");这种方法转换成 iso 8601标准字符串格式
                lstRealDataFile.Add(DateTime.Now.ToString("s"));
                if (Program.SqliteDB.InsertRealDataFile(lstRealDataFile, imgCurXh.ToString()) == 1)
                {
                    MessageBox.Show("保存成功!", this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                lstRealDataFile.Clear();
                lstRealDataFile = null;
            }
        }

        private void diagnostics_Click(object sender, EventArgs e)
        {
            var diagnostics = new Diagnostics(new WinFormsWindowMessageHook(this));
        }
        //主键
        public Int32 CurHtID = 0;
        //合同编号
        public string CurHtbh = "";
        //合同名称
        public string CurHtmc = "";
        //年份
        public string CurHtqdrq = "";
        string ImgFolder = "";
        private void Frm_Scan_Load(object sender, EventArgs e)
        {
            //窗体最大化
            this.Height = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
            this.CenterToScreen();
            this.Text += string.Format("【合同编号：{0} 合同名称：{1}】", CurHtbh, CurHtmc);
            //图像路径
            ImgFolder = Program.APPdirPath + @"\ContractScan_Image";
            if (Directory.Exists(ImgFolder) == false)
            {
                Directory.CreateDirectory(ImgFolder);
            }
        }

        private void Frm_Scan_FormClosing(object sender, FormClosingEventArgs e)
        {
            //更新合同扫描标记
            string sqlstr = "select max(timestamp) from multi_media_info where media_type=1 and study_no=" + CurHtID;
            object imgXh = Program.SqliteDB.ExecuteScalar(sqlstr);
            if (imgXh != null && imgXh.ToString() != "")
            {
                sqlstr = "update ht_info set scan_flag=1 where id="+CurHtID;
                Program.SqliteDB.ExecuteNonQuery(sqlstr);
            }
        }
    }
}
